<template>
	<div>
		<!-- <el-upload ref="uoload" v-if="type == 'file'" :action="`${Config.baseUrl.dev}/systemAnnex/upload`" :limit="maxLength"
			:file-list="fileListHttp" :headers="headers" :auto-upload="uploadData.iid?autoUpload:false"
			:on-change="onChange" :accept="accept" :before-remove="handleRemove" :data="uploadData" :disabled="disabled" name="files" :http-request="true">
			<i class="el-icon-upload"></i>
			<div class="el-upload__text"><em>点击上传</em></div>
		</el-upload> -->
		<div class="img-box">
			<!-- <div v-loading="cameraLoading" v-if="!disabled">
				<div class="flex-c flex-con flex-align" style="width: 148px; height: 148px;border-radius: 10px;position: relative;overflow: hidden;text-align: center;vertical-align: middle;background-color: #fbfdff;
    border: 1px dashed #c0ccda;">
					<i class="el-icon-error" v-if="!disabled && src"
						style="color: red;font-size: 20px;float: left;position: absolute;right: 5px;bottom: 5px;z-index: 2;background-color: #fff;border-radius: 50%;cursor: pointer;"
						@click="src = null"></i>
					<div class="flex-r flex-con flex-align" v-if="!disabled && src"
						style="color: #fff;font-size: 14px;float: left;position: absolute;left: 5px;bottom: 5px;z-index: 2;background-color: #00c14d;border-radius: 5px;cursor: pointer;height: 20px;padding: 5px;"
						@click="uploadCameraFile">
						<i class="el-icon-upload" style="color: #fff;"></i>
						上传
					</div>
					<div v-if="!src" @click="grabimage" style="color: #999;">
						<i class="el-icon-camera-solid" style="font-size: 50px;margin: 0 auto;display: block;"></i>
						<span>拍照</span>
					</div>
					<el-image style="width: 100%;height: 100%;" v-if="src" :src="src" :preview-src-list="[src]">
						<div slot="error" class="image-slot">
							<i class="el-icon-picture-outline"></i>
						</div>
					</el-image>
				</div>
			</div> -->
			<div>
				<el-upload ref="uoload" v-if="!disabled" :action="`${Config.baseUrl.dev}/systemAnnex/upload`"
					list-type="picture-card" :limit="maxLength" :on-exceed="handleExceed" :file-list="fileRawList"
					:headers="headers" :auto-upload="false" :on-change="onChange" :on-preview="handlePictureCardPreview"
					:accept="accept" :before-remove="handleRemove" :data="uploadData" :disabled="disabled"
					:multiple="true">
					<i class="el-icon-plus"></i>
				</el-upload>
			</div>
			<div v-for="(item,key) in fileListHttp" :key="key">
				<div style="width: 148px; height: 148px;border-radius: 10px;position: relative;overflow: hidden;">
					<i class="el-icon-error" v-if="!disabled"
						style="color: red;font-size: 20px;float: left;position: absolute;right: 5px;bottom: 5px;z-index: 2;background-color: #fff;border-radius: 50%;cursor: pointer;"
						@click="handleRemove(item)"></i>
					<el-image style="width: 100%;height: 100%;" :src="item.url" :preview-src-list="urlList">
						<div slot="error" class="image-slot">
							<i class="el-icon-picture-outline"></i>
						</div>
					</el-image>
				</div>
			</div>
		</div>
		<el-dialog :visible.sync="dialogVisible" title="图片预览">
			<img width="100%" :src="dialogImageUrl" alt="">
		</el-dialog>
	</div>
</template>

<script>
	export default {
		name: 'upLoadImg',
		components: {},
		props: {
			'maxLength': {}, //总数
			'placeholder': {}, //提示文字
			'fileList': {}, //反显附件列表
			'name': {}, //字段名
			//自动上传
			"autoUpload": {
				default: false,
			},
			type: {
				default: 'img'
			},
			//附件类型
			accept: {
				default: '*'
			},
			//附件传参。
			uploadData: {
				default: {}
			},
			//是否禁用上传
			disabled: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				Config: {
					baseUrl:{
						dev:'123'
					}
				},
				fileListHttp: [],
				headers: {
					Authorization: sessionStorage.getItem('token_permissions')
				},
				url: process.env.VUE_APP_URL,
				dialogImageUrl: null,
				dialogVisible: false,
				fileRawList: [],
				urlList: [],
				funUrl: '/systemAnnex/uploadList',
				iid: null,
				src: null,
				cameraLoading: false,
			};
		},
		watch: {
			uploadData: {
				handler(a) {
					if (a.iid && a.iid != this.uploadData.iid) {
						this.setFileList()
					}
					this.uploadData = a;
				},
				deep: true, // 深度监听

			},
			closeBtn(e) {
				this.closeBtn = a
			},
			fileList(a) {
				if (this.uploadData.iid) {
					this.fileList = a
					this.setFileList()
				}
			}
		},
		created() {
			// this.$axiosaj.get("http://127.0.0.1:38088/video=stream&camidx=0?"+Math.random())
			this.setFileList()
		},
		methods: {
			grabimage() {
				this.cameraLoading = true;
				let filePath = this.$store.getters.getSystemData('webCamera')[0].typeCode
				var msg1 = {
					"filepath": `${filePath}\\${this.uploadData.name}_${this.uploadData.fileTypeCode}.jpg`,
					"rotate": "",
					"deskew": "",
					"deskewval": "",
					"camidx": "0",
					"ColorMode": "",
					"quality": "1",
					"bAutoAdjust": "",
					"bIsPrint1to1": "",
					"watermark": {
						"pos": "",
						"content": "",
						"transparency": "",
						"fontsize": "",
						"font": "",
						"color": ""
					}
				};
				this.$axiosaj.post("http://127.0.0.1:38088/video=grabimage", msg1).then(response => {
					console.log(' successfully:', response);
					this.cameraLoading = false;
					this.src = "data:image/png;base64," + response.data.photoBase64;


				})
			},
			uploadCameraFile() {
				let file = this.base64toBlob(this.src, 'file')
				let formdata = new FormData();
				formdata.append("file", file);
				formdata.append("iid", this.uploadData.iid || this.iid);
				formdata.append("fileTypeCode", this.uploadData.fileTypeCode);
				this.$axios.post('/systemAnnex/upload', formdata).then(res => {
					if (res.code == 200) {
						this.src = null
						this.$emit('uploadOk')
					}
				})
			},
			// 将base64转换为blob
			base64toBlob(dataurl) {
				let arr = dataurl.split(","),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n);
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n);
				}
				let blob = new Blob([u8arr], {
					type: mime
				})
				return new File([blob], 'webPhoto.jpg')
			},
			setFileList() {
				if (this.fileList && this.fileList.indexOf(',') != -1) {
					let arr = this.fileList.split(',')
					this.fileListHttp = arr.map((v, i) => {
						this.urlList.push(this.Config.baseUrl.dev + v.filePath)
						return {
							name: v.fileName,
							url: this.Config.baseUrl.dev + v.filePath,
							fileId: v.fileId
						}
					})
				} else {
					if (this.fileList && this.fileList.length > 0) {
						this.fileListHttp = this.fileList.map((v, i) => {
							this.urlList.push(this.Config.baseUrl.dev + v.filePath)
							return {
								name: v.fileName,
								url: this.Config.baseUrl.dev + v.filePath,
								fileId: v.fileId
							}
						})
					} else {
						this.fileListHttp = []
					}
				}
			},
			beforeUpload(file, fileList) {

				// return false
			},
			handleRemove(file, fileList) {

				// this.fileListHttp = this.fileListHttp.filter(v=>v.name != file.name)
				this.$axios.get('/systemAnnex/deleteFile', {
					params: {
						iid: file.fileId
					}
				}).then(res => {
					if (res.code == 200) {
						this.$emit('uploadOk')
					}
				})
			},
			handlePreview(file) {

			},
			handleExceed(files, fileList) {
				this.$message.warning(`当前限制选择${this.maxLength}个文件`);
			},
			beforeRemove(file, fileList) {
				return this.$confirm(`确定移除 ${ file.name }？`);
			},
			onChange(file, fileList) {
				if (this.uploadData.iid || this.iid) {
					//有iid 单附件上传
					if (this.autoUpload) {
						this.fileRawList = []
						let formdata = new FormData();
						formdata.append("file", file.raw);
						formdata.append("iid", this.uploadData.iid || this.iid);
						formdata.append("fileTypeCode", this.uploadData.fileTypeCode);
						this.$axios.post('/systemAnnex/upload', formdata).then(res => {
							if (res.code == 200) {
								this.$emit('uploadOk')
							}
						})
					}
				} else {
					//没有根据父页面调用 submitUpload 多附件上传。
					this.fileRawList = fileList
					this.$emit('fileLength', fileList)
				}
			},
			handlePictureCardPreview(file) {
				this.dialogImageUrl = file.url;
				this.dialogVisible = true;
			},
			submitUpload(iid) {
				// this.$refs.uoload.submit()
				if (this.fileRawList.length > 0) {
					let formdata = new FormData();
					let typeCodes = []
					this.fileRawList.forEach(file => {
						formdata.append("files", file.raw);
						typeCodes.push({
							code: this.uploadData.fileTypeCode,
							name: file.name
						})
					})
					formdata.append("iid", this.uploadData.iid || iid);
					formdata.append("typeCodes", JSON.stringify(typeCodes));
					this.$axios.post(this.funUrl, formdata).then(res => {
						if (res.code == 200) {
							this.$emit('uploadOk')
						}
					})
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.img-box {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;

		>div {
			margin: 10px;
		}
	}
</style>